import { defineStore } from 'pinia';

// 定义不同路由下的情景提示
const contextualTips = {
  TeacherDashboard: {
    message: "欢迎回到工作台！<br>您可以从这里的快捷入口开始一天的工作。",
    mood: 'happy',
  },
  TeacherCreateExam: {
    message: "进入了智能组卷页面！<br>您可以尝试输入：<b>‘一份关于《高等数学》中“极限与连续”章节的期中测试’</b>，AI会帮您生成一份高质量的试卷哦。",
    mood: 'idle',
  },
  TeacherAutoGrader: {
    message: "这里是AI学情分析中心。<br>请分别上传<b>包含标准答案的试卷</b>和<b>纯文本的学生答卷</b>，AI就能为您生成一份详细的分析报告！",
    mood: 'thinking',
  },
  TeacherLiveRoom: {
    message: "直播间准备就绪！<br>作为老师(publisher)，您可以开启摄像头和麦克风，还可以<b>发起随堂测验</b>与学生互动哦。",
    mood: 'happy',
  }
};

let lastShownRoute = null;
let inactivityTimer = null;
const INACTIVITY_TIMEOUT = 5000; // 5秒

export const useMascotStore = defineStore('mascot', {
  state: () => ({
    isVisible: false,
    message: '',
    buttons: [],
    mood: 'idle',
    energy: 5, // 活力值上限改为 10
  }),
  actions: {
    show(message, options = {}) {
      this.message = message;
      this.buttons = options.buttons || [];
      this.mood = options.mood || 'idle';
      this.isVisible = true;
    },

    hide() {
      this.isVisible = false;
      this.message = '';
      this.buttons = [];
      this.mood = 'idle';
    },

    setMood(mood) {
      if (this.isVisible) {
        this.mood = mood;
      }
    },

    updateEnergy(newEnergy) {
      this.energy = Math.max(0, Math.min(5, newEnergy)); // 【改动】确保活力值在 0-5

      // 【改动】根据新的活力阈值更新心情
      if (this.energy >= 4) { // 活力值为 4 或 5 时
        this.mood = 'happy';
      } else if (this.energy >= 2) { // 活力值为 2 或 3 时
        this.mood = 'idle';
      } else { // 活力值为 1 或 0 时
        this.mood = 'sleepy';
      }
    },

    gainEnergyOnActivity() {
      this.updateEnergy(this.energy + 1);
      this.resetInactivityTimer();
    },

    decreaseEnergy() {
      this.updateEnergy(this.energy - 1);
      if (this.energy > 0) {
        this.resetInactivityTimer();
      }
    },

    resetInactivityTimer() {
      if (inactivityTimer) {
        clearTimeout(inactivityTimer);
      }
      inactivityTimer = setTimeout(() => {
        this.decreaseEnergy();
      }, INACTIVITY_TIMEOUT);
    },

    triggerContextualTip(routeName) {
      if (lastShownRoute === routeName) {
        return;
      }

      const tip = contextualTips[routeName];
      this.hide();
      lastShownRoute = routeName;

      if (tip) {
        setTimeout(() => {
          if (lastShownRoute === routeName) {
            this.show(tip.message, { mood: tip.mood });
          }
        }, 400);
      }
    }
  },
});